package com.zhou.job;

import com.zhou.pojo.Register;
import com.zhou.service.impl.EurekaServiceImpl;
import com.zhou.utils.TimeDifferenceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class MyJob {
    @Autowired
    private EurekaServiceImpl eurekaService;

    //3.添加定时任务
    @Scheduled(cron = "0/59 * * * * ?")
    private void configureTasks() throws ParseException {
        //查询所有数据
        List<Register> registers = eurekaService.findAll();
        for (Register register : registers) {
            String oldStatus = register.getStatus();  //心跳最后一次存入数据库时间
            String nowStatus = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); //现在时间
            //比较存入数据库的最后时间和现在时间差值,大于90认为不可用,剔除服务
            if (TimeDifferenceUtil.compare(nowStatus, oldStatus) > 90) {
                System.out.println("start  Job：剔除服务");
                eurekaService.delete(register.getId());
            }
        }

    }
}
